package HtServer.FileUpload;

import HtServer.meeting.MeetingItem;
import HtServer.meeting.MeetingItems;
import HtServer.returnObject.ReturnObject;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import tools.ImageTools;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "FileUploadTempServletTemp", value = "/uploadTemp")
@MultipartConfig
public class MeetingFileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "uploads";
    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 获取文件上传的部分
        Part filePart = request.getPart("file");
        String userid = request.getParameter("userid");
        System.out.println("userid = "+userid);
        ReturnObject rto = new ReturnObject();

        // 获取上传的文件名
        String fileName = filePart.getSubmittedFileName();

        // 定义文件保存路径
        String filePath ="";
        File uploadDir = new File(getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        filePath = uploadDir + File.separator + fileName;
        // 保存文件
        filePart.write(filePath);
        try
        {
            MeetingItem mi = MeetingItems.getInstance().getMeetingItem(userid);

            mi.setImage(ImageTools.encodeImageToBase64(filePath));
            mi.saveMeetingItem2Redis();

        }
        catch (Exception e)
        {
            System.err.println("error in uploadTempServlet"+e.getMessage());
//                           e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        writer.println(JSON.toJSON(rto).toString());
        writer.flush();
        writer.close();



    }
}